package cn.wzg.server.Servers.Handler;

import cn.wzg.entity.Request;
import cn.wzg.entity.Response;
import cn.wzg.server.Service.ServiceProvider;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.AllArgsConstructor;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

@AllArgsConstructor
public class NettyRPCServerHandler extends SimpleChannelInboundHandler<Request> {
    ServiceProvider serviceprovider;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Request msg) throws Exception {
        System.out.println("nettyRequest开始处理请求");
        Response response = getResponse(msg);
        System.out.println("输出响应结果"+response);
        ctx.writeAndFlush(response);
        ctx.close();
    }
    Response getResponse(Request request) {
        // 得到服务名
        String interfaceName = request.getInterfaceName();
        // 得到服务端相应服务实现类
        Object service = serviceprovider.getService(interfaceName);
        // 反射调用方法
        Method method = null;
        try {
            method = service.getClass().getMethod(request.getMethodName(), request.getParamsTypes());
            Object invoke = method.invoke(service, request.getParams());
            return Response.success(invoke);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            System.out.println("方法执行错误");
            return Response.fail();
        }
    }
}
